<template>
  <view class="payment-type-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">驶离欠费统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
               <text class="filter-label">欠费类型：</text>
               <picker :value="filters.arrearsTypeIndex" :range="arrearsTypes.map(item => item.name)" @change="onArrearsTypeChange">
                  <view class="date-picker">
                   <text>{{ filters.arrearsTypeIndex >= 0 ? arrearsTypes[filters.arrearsTypeIndex].name : '全部' }}</text>
                   <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">总欠费金额</view>
            <view class="summary-value">{{ summary.totalArrears }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">总欠费笔数</view>
            <view class="summary-value">{{ summary.totalCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">平均欠费金额</view>
            <view class="summary-value">{{ summary.avgArrears }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">欠费类型</text>
          <text class="list-cell">欠费金额</text>
          <text class="list-cell">欠费笔数</text>
          <text class="list-cell">占比</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="openDetail(item)">
        <view class="list-cell transaction-cell">
          <view class="transaction-tag arrears-tag">
            {{ item.arrearsTypeName }}
          </view>
        </view>
        <text class="list-cell">{{ item.amount }}元</text>
        <text class="list-cell">{{ item.count }}笔</text>
        <text class="list-cell">{{ item.percentage }}%</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ currentDetail ? currentDetail.arrearsTypeName + ' 详情' : '详情信息' }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">欠费类型：</text>
            <view class="detail-value">
              <view class="transaction-tag arrears-tag">
                {{ currentDetail.arrearsTypeName }}
              </view>
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">欠费金额：</text>
            <text class="detail-value">{{ currentDetail.amount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">欠费笔数：</text>
            <text class="detail-value">{{ currentDetail.count }}笔</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占比：</text>
            <text class="detail-value">{{ currentDetail.percentage }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均欠费金额：</text>
            <text class="detail-value">{{ currentDetail.avgAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最高欠费金额：</text>
            <text class="detail-value">{{ currentDetail.maxAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">最低欠费金额：</text>
            <text class="detail-value">{{ currentDetail.minAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.timeDistribution && currentDetail.timeDistribution.length > 0">
            <text class="detail-label">时段分布：</text>
            <view class="detail-value">
              <view v-for="(time, idx) in currentDetail.timeDistribution" :key="idx" class="time-item">
                {{ time.name }}: {{ time.count }}笔 ({{ time.percentage }}%)
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选表单
const filters = reactive({
  periodIndex: 0,
  arrearsTypeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 欠费类型
const arrearsTypes = [
  { name: '全部', value: 'all' },
  { name: '驶离无牌', value: 'no_plate' },
  { name: '封顶欠费', value: 'cap_arrears' },
  { name: '普通欠费', value: 'normal_arrears' }
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  totalArrears: '0.00元',
  totalCount: '0笔',
  avgArrears: '0.00元'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 欠费类型选择处理
const onArrearsTypeChange = (e) => {
  filters.arrearsTypeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.arrearsTypeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算总金额和总次数
  let totalArrears = 0
  let totalCount = 0
  
  data.forEach(item => {
    // 计算总欠费金额和笔数
    totalArrears += parseFloat(item.amount)
    totalCount += item.count
  })
  
  // 计算平均欠费金额
  const avgArrears = totalCount > 0 ? (totalArrears / totalCount).toFixed(2) : '0.00'
  
  // 更新摘要数据
  summary.totalArrears = totalArrears.toFixed(2) + '元'
  summary.totalCount = totalCount + '笔'
  summary.avgArrears = avgArrears + '元'
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 时段分布
  const timeDistributions = [
    { name: '早上(6:00-10:00)', value: 'morning' },
    { name: '中午(10:00-14:00)', value: 'noon' },
    { name: '下午(14:00-18:00)', value: 'afternoon' },
    { name: '晚上(18:00-22:00)', value: 'evening' },
    { name: '深夜(22:00-6:00)', value: 'night' }
  ]
  
  // 筛选欠费类型
  let filteredArrearsTypes = [...arrearsTypes.slice(1)] // 排除'全部'选项
  if (filters.arrearsTypeIndex > 0) { // 0是全部，大于0才需要筛选
    filteredArrearsTypes = [arrearsTypes[filters.arrearsTypeIndex]]
  }
  
  // 计算总欠费金额和总次数（用于计算占比）
  const totalArrearsAmount = Math.floor(Math.random() * 50000) + 10000 // 10000-60000元
  const totalArrearsCount = Math.floor(Math.random() * 1000) + 200 // 200-1200笔
  
  // 生成随机数据
  for (const arrearsType of filteredArrearsTypes) {
    // 根据欠费类型设置不同的分布
    let amountPercentage, countPercentage
    
    if (arrearsType.value === 'no_plate') {
      amountPercentage = Math.random() * 0.15 + 0.2 // 20%-35%
      countPercentage = Math.random() * 0.15 + 0.25 // 25%-40%
    } else if (arrearsType.value === 'cap_arrears') {
      amountPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
      countPercentage = Math.random() * 0.2 + 0.35 // 35%-55%
    } else {
      amountPercentage = Math.random() * 0.15 + 0.15 // 15%-30%
      countPercentage = Math.random() * 0.1 + 0.1 // 10%-20%
    }
    
    const amount = Math.floor(totalArrearsAmount * amountPercentage)
    const count = Math.floor(totalArrearsCount * countPercentage)
    
    // 计算占比（相对于总欠费金额）
    const percentage = ((amount / totalArrearsAmount) * 100).toFixed(2)
    
    // 计算平均金额
    const avgAmount = count > 0 ? (amount / count).toFixed(2) : '0.00'
    
    // 生成最高和最低欠费金额
    const maxAmount = parseFloat(avgAmount) * (Math.random() * 3 + 2).toFixed(2) // 平均金额的2-5倍
    const minAmount = parseFloat(avgAmount) * (Math.random() * 0.5 + 0.1).toFixed(2) // 平均金额的10%-60%
    
    // 生成时段分布
    const timeDistributionDetails = []
    let remainingTimeCount = count
    
    for (let j = 0; j < timeDistributions.length; j++) {
      let timeCount
      if (j === timeDistributions.length - 1) {
        timeCount = remainingTimeCount
      } else {
        timeCount = Math.floor(count * (Math.random() * 0.3 + 0.05)) // 5%-35%
        remainingTimeCount -= timeCount
      }
      
      const timePercentage = ((timeCount / count) * 100).toFixed(2)
      
      timeDistributionDetails.push({
        name: timeDistributions[j].name,
        count: timeCount,
        percentage: timePercentage
      })
    }
    
    // 添加数据
    data.push({
      id: data.length + 1,
      arrearsTypeName: arrearsType.name,
      arrearsTypeValue: arrearsType.value,
      amount: amount.toFixed(2),
      count,
      percentage,
      avgAmount,
      maxAmount,
      minAmount,
      timeDistribution: timeDistributionDetails
    })
  }
  
  // 根据金额排序（从多到少）
  return data.sort((a, b) => parseFloat(b.amount) - parseFloat(a.amount))
}

// 打开详情弹窗
const openDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.payment-type-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  margin: 20rpx;
  
  .summary-card {
    flex: 1;
    background: white;
    padding: 20rpx;
    border-radius: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    text-align: center;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background-color: #f5f7fa;
  padding: 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 20rpx 20rpx 0 0;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}

.list-row {
  display: flex;
  background-color: white;
  padding: 30rpx 20rpx;
  margin: 0 20rpx;
  border-bottom: 1px solid #f0f0f0;
  font-size: 28rpx;
  color: #333;
  
  &:last-child {
    border-radius: 0 0 20rpx 20rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  display: flex;
  align-items: center;
}

.transaction-cell {
  display: flex;
  align-items: center;
}

.transaction-tag {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.arrears-tag {
  background-color: #ff6b6b;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    padding: 0 20rpx;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
  
  .detail-item {
    margin-bottom: 20rpx;
    display: flex;
    
    .detail-label {
      width: 200rpx;
      font-size: 28rpx;
      color: #666;
    }
    
    .detail-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .time-item {
      margin-bottom: 10rpx;
    }
  }
}
</style>